import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:talk/pages/device/x_device_router.dart';

import '../../api/AlarmApi.dart';
import '../../api/DeviceApi.dart';
import '../../commponets/CustomSwitch.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../utils/toast_utils.dart';
import '../provider/CustomBottomPicker.dart';
import 'model/Device.dart';
import 'model/DeviceAlarm.dart'; // 添加导入

class DeviceAlarmPage extends StatefulWidget {
  const DeviceAlarmPage({
    super.key,
    this.deviceId,
    this.device,
  });

  final int? deviceId;
  final Device? device;

  @override
  State<DeviceAlarmPage> createState() => _DeviceAlarmPageState();
}

class _DeviceAlarmPageState extends State<DeviceAlarmPage> {
  final DeviceApi _deviceApi = DeviceApi();
  final AlarmApi _alarmApi = AlarmApi();
  late int _deviceId;
  Device? _device;
  List<DeviceAlarm> _deviceAlarms = []; // 存储设备报警数据
  bool _isLoading = true; // 加载状态
  late int interCom; // 对讲状态变量
  //app报警
  late int interAppAlarm;

  @override
  void initState() {
    super.initState();

    _deviceId = widget.deviceId!;
    _device = widget.device!;

    interCom = _device?.timeWatermark ?? 0; // 初始化时同步timeWatermark的值
    interAppAlarm = _device?.appMessage ?? 0; // 初始化时同步timeWatermark的值
    _fetchData();
  }

  Future<void> _fetchData() async {
    try {
      final response = await _deviceApi.getDeviceAlarm(_deviceId);
      if (response.code == 200) {
        // 解析数据
        setState(() {
          _deviceAlarms = (response.rows as List<dynamic>)
              .map((item) => DeviceAlarm.fromJson(item))
              .toList();
          _isLoading = false;
        });
      } else {
        Toast.show("获取数据失败，错误码: ${response.code}");
        setState(() => _isLoading = false);
      }
    } catch (e) {
      // Toast.show("网络请求错误: $e");
      Toast.show("网络请求错误");
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('d_baojingshezhi'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),
      body: Container(
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : ListView(
          padding: const EdgeInsets.all(16.0),
          children: [
            const SizedBox(height: 20),

            // 构建摄像头列表
            ..._deviceAlarms.map((alarm) {
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 0.0),
                child: ItemView(
                  width: double.infinity,
                  height: 50,
                  leftPadding: 10,
                  rightPadding: 20,
                  leftWidget: Row(
                    children: [
                      const SizedBox(width: 10),
                      Text(
                        alarm.camName ?? AppLocale.text('d_weizhi'),
                        style: const TextStyle(
                          fontSize: 15.0,
                          color: Colors.black,
                        ),
                      ),
                    ],
                  ),
                  borderRadius: 8,
                  // onTap: () {
                  //   print('点击了摄像头: ${alarm.camId}');
                  // },


                  onTap: () {
                    final deviceAlarmJson = json.encode(alarm.toJson());
                    final encodedDeviceAlarm = Uri.encodeComponent(deviceAlarmJson);
                    NavigatorUtils.push(
                      context,
                      '${XDeviceRouter.deviceAlarmInfoPage}?deviceId=$_deviceId&deviceAlarm=$encodedDeviceAlarm',
                    );
                  },
                ),
              );
            }).toList(),

            const SizedBox(height: 20),


            ItemView(
              width: double.infinity,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  const SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_iobaojing'),
                    style: TextStyle(
                      fontSize: 15.0,
                      color: Colors.black,
                    ),
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {
                // dynamic ioSelect = 1;
                dynamic ioSelect = _device?.ioAlarm;

                // 选项列表（label 是显示文案，value 是实际值）
                List<Map<String, dynamic>> ioList = [
                  {'label': AppLocale.text('d_changgui'), 'value': 0},
                  {'label': AppLocale.text('d_lvxing'), 'value': 1},
                  {'label': AppLocale.text('d_lijia'), 'value': 2},
                  {'label': AppLocale.text('d_zaijia'), 'value': 3},
                  {'label': AppLocale.text('d_ECO'), 'value': 4},
                  {'label': AppLocale.text('d_jingyin'), 'value': 5},
                ];

                showModalBottomSheet(
                  context: context,
                  backgroundColor: Colors.transparent,
                  builder: (BuildContext dialogContext) {
                    return CustomBottomPicker(
                      title: AppLocale.text('d_iobaojing'),
                      height: 300,
                      list: ioList,
                      selectedColor: Colors.blue,
                      backgroundColor: Colors.white,
                      initialValue: ioSelect,
                      //圆圈样式
                      selectedShapeType: SelectedShapeType.hollowCircle,
                      onSelect: (newValue) {
                        // 选中值变化时的回调，可在此更新页面状态
                        setState(() {
                          // 示例：如果需要把 newValue 存到 _device 或其他变量，可自行处理
                          // _device.someProperty = newValue;
                          // ioSelect = newValue; // 更新假数据
                          _device?.ioAlarm = newValue; // 更新假数据
                        });

                        final toUpdate = {
                          "deviceId": _device?.deviceId,
                          "ioAlarm": newValue,
                        };
                        _alarmApi.updateIoAlarm(toUpdate);
                      },
                    );
                  },
                );
              },
            ),


            ItemView(
              width: 400,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  const SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_appxiaoxitixing'),
                    style: TextStyle(fontSize: 15.0, color: Colors.black),
                  ),
                ],
              ),
              rightWidget: Row(
                children: [
                  CustomSwitch(
                    value: _device?.appMessage ?? 0,
                    size: 25.0,
                    onChanged: (newValue) {
                      setState(() {
                        _device?.appMessage = newValue;
                        interAppAlarm = newValue; // 同步更新interCom的值
                      });

                      final toUpdate = {
                        "deviceId": _device?.deviceId,
                        "appMessage": newValue,
                      };
                      _alarmApi.appMessageAlarm(toUpdate);
                    },
                    activeBackgroundColor: Colors.green,
                    inactiveBackgroundColor: Colors.grey[300]!,
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {},
            ),


          ],
        ),
      ),
    );
  }
}    